package com.hymall.util;

import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 从40期找到的加密工具类
 *
 * @author: 叶熠彬
 * @date: 2022/7/18 17:48
 * @param:
 * @return:
 */
public class Md5Util {

    /**
     * 这次数据库存储的都是不加盐加密的算法
     *
     * @author: 叶熠彬
     * @date: 2022/7/18 17:56
     * @param: [content]
     * @return: java.lang.String
     */
    public static String getMd5(String content) {
        //获得消息消息摘要算法
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("md5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        byte[] contentBytes = content.getBytes();
        byte[] resultBytes = messageDigest.digest(contentBytes);//byte 8 2^8 ff
        int length = resultBytes.length;
        StringBuffer stringBuffer = new StringBuffer();
        for (byte resultByte : resultBytes) {
            int temp = resultByte & 0xff; //0-255
            String s = Integer.toHexString(temp); //0-15 0a  05 0-f
            if (s.length() == 1) {
                stringBuffer.append(0);
            }
            stringBuffer.append(s);
        }
        return stringBuffer.toString();


    }

    //加盐后加密
    public static String getMd5(String content, String salt) throws Exception {
        content = content + "&" + salt + "}";
        return getMd5(content);
    }

    //加盐后加密
    public static String getMultyMd5(String content) throws Exception {
        return getMd5(getMd5(getMd5(content)), "123456");
    }

    //文件加密
    public static String getFileMd5(File file) throws Exception {
        MessageDigest messageDigest = MessageDigest.getInstance("md5");

        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] bytes = new byte[1024];
        int length = 0;
        while ((length = fileInputStream.read(bytes, 0, 1024)) != -1) {
            messageDigest.update(bytes, 0, bytes.length);
        }
        byte[] resultBytes = messageDigest.digest();
        StringBuffer stringBuffer = new StringBuffer();
        for (byte resultByte : resultBytes) {
            int temp = resultByte & 0xff; //0-255
            String s = Integer.toHexString(temp); //0-15 0a  05 0-f
            if (s.length() == 1) {
                stringBuffer.append(0);
            }
            stringBuffer.append(s);
        }
        return stringBuffer.toString();
    }
}
